package com.jy.appmarket.activity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.json.JSONObject;

import com.jy.app.market.idata.data.Ad;
import com.jy.app.market.idata.data.Download;
import com.jy.app.market.idata.data.GuideRecommendation;
import com.jy.app.market.idata.data.Link;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.network.engine.HotWordsNetEngine;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.newnetwork.RequestQueue;
import com.jy.appmarket.newnetwork.Response.Listener;
import com.jy.appmarket.newnetwork.api.ApiRequest;
import com.jy.appmarket.newnetwork.api.ApiResult;
import com.jy.appmarket.newnetwork.api.MarketApi;
import com.jy.appmarket.screenlock.database.CustomMessageDB;
import com.jy.appmarket.screenlock.database.CustomMessageTb;
import com.jy.appmarket.screenlock.utils.CustomMessageUtils;
import com.jy.appmarket.screenlock.utils.LockScreenConfig;
import com.jy.appmarket.service.NotificationService;
import com.jy.appmarket.service.PollService;
import com.jy.appmarket.service.UpdateService;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.AdManager;
import com.jy.appmarket.utils.ApkRecommendHolder;
import com.jy.appmarket.utils.LocationUtil;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.utils.Prefs;
import com.jy.appmarket.utils.StorageConfig;
import com.jy.appmarket.utils.SysUtils;
import com.jy.appmarket.widget.CirclePageIndicator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;

public class LoadingActivity extends Activity implements Listener<ApiResult> {
	private static final String TAG = LoadingActivity.class.getSimpleName();
	private static Handler sHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		cacheHotWords();
		initResources(this);

		if (Prefs.getGuideVersion(this) != getVersionCode(this)) {
			showGuide();
		} else {
			showAd();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mQueue != null) {
			mQueue.stop();
		}
	}

	//////////////////////////////////////////////////////////////////////////////////////
	// 引导页面相关代码
	private static int[] sGuideImages = { R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3,
			R.drawable.guide_4, R.drawable.guide_5 };
	private RequestQueue mQueue;
	private DownloadItem mDownloadItem;

	private DownloadItem loadGuideApp() {
		try {
			byte[] bytes = SysUtils.assetFile2Bytes(this, "guide_app");
			JSONObject json = new JSONObject(new String(bytes, "UTF-8"));
			DownloadItem di = new DownloadItem();
			di.setName(json.getString("name"));
			di.setDlUrl(json.getString("dlUrl"));
			di.setIconUrl(json.getString("iconUrl"));
			di.setPkgName(json.getString("pkgName"));
			di.setVersionCode(json.getInt("versionCode"));
			di.setVersionName(json.getString("versionName"));
			di.setMd5(json.getString("md5"));
			di.setTotalSize(json.getInt("fileSize"));
			return di;
		} catch (Exception e) {
		}
		return null;
	}

	private boolean shouldShowApp(String pkgName) {
		if (TextUtils.isEmpty(pkgName)) {
			return false;
		}
		if (PackageUtils.isPackageInstalled(this, pkgName)) {
			return false;
		}
        return !DownloadUtils.downloadExist(this, pkgName);
    }

	@SuppressWarnings("deprecation")
	private void showGuide() {
		mDownloadItem = loadGuideApp();
		setContentView(R.layout.activity_guide);
		ViewPager pager = findViewById(R.id.pager);
		List<Drawable> guides = new ArrayList<Drawable>();

		for (int id : sGuideImages) {
			try {
				guides.add(getResources().getDrawable(id));
			} catch (Exception e) {
			}
		}
		pager.setAdapter(new GuidePagerAdapter(guides));
		CirclePageIndicator indicator = findViewById(R.id.guide_indicator);
		indicator.setViewPager(pager);
		View entryView = findViewById(R.id.guide_enter_view);

		if (guides.size() == 0 || guides.size() == 1) {
			entryView.setVisibility(View.VISIBLE);
			if (mDownloadItem == null || !shouldShowApp(mDownloadItem.getPkgName())) {
				findViewById(R.id.guide_checkbox).setVisibility(View.INVISIBLE);
			}
		} else {
			pager.addOnPageChangeListener(new GuideChangedListener(guides.size(), entryView));
		}

		ApiRequest api = ApiRequest.get("guide_recommendation", this, null);
		mQueue = MarketApi.newApiRequestQueue(this);
		mQueue.add(api);
		findViewById(R.id.guide_enter_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				CheckBox cb = findViewById(R.id.guide_checkbox);
				if (cb.getVisibility() == View.VISIBLE && cb.isChecked()) {
					Intent it = new Intent(v.getContext(), DownloadService.class);
					it.setAction(DownloadService.ACTION_START_DOWNLOAD);
					mDownloadItem.setSource(new ApkSource("guide_recommendation").toSourceString());
					it.putExtra(DownloadService.EXTRA_DOWNLOADMODEL, mDownloadItem);
					startService(it);
				}
				Prefs.setGuideVersion(v.getContext(), getVersionCode(v.getContext()));
				enterMain(null);
			}
		});
	}

	private void setCheckbox(DownloadItem di) {
		CheckBox checkbox = findViewById(R.id.guide_checkbox);

		if (di != null && shouldShowApp(mDownloadItem.getPkgName())) {
			checkbox.setText("推荐安装：" + di.getName());
			checkbox.setVisibility(View.VISIBLE);
		} else {
			checkbox.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public void onResponse(ApiResult response) {
		// 引导推荐
		if (!response.isOK()) {
			LogUtil.d(TAG, "falied to get guide rec");
			return;
		}
		GuideRecommendation rec = response.getData(GuideRecommendation.class);
		if (rec == null) {
			return;
		}
		Download dl = rec.getDownload();
		if (dl == null) {
			return;
		}
		DownloadItem di = new DownloadItem();
		di.setDlUrl(dl.getDlUrl());
		di.setTotalSize(dl.getFileSize());
		di.setIconUrl(dl.getIconUrl());
		di.setMd5(dl.getMd5());
		di.setName(dl.getName());
		di.setPkgName(dl.getPkgName());
		di.setVersionCode(dl.getVersionCode());
		di.setVersionName(dl.getVersionName());
		mDownloadItem = di;
		setCheckbox(mDownloadItem);
	}

	private class GuideChangedListener implements ViewPager.OnPageChangeListener {
		private final int pagerSize;
		private final View lastToShow;

		public GuideChangedListener(int size, View v) {
			pagerSize = size;
			lastToShow = v;
		}

		@Override
		public void onPageScrollStateChanged(int state) {
		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
			if (position == pagerSize - 1) {
				setCheckbox(mDownloadItem);
				lastToShow.setVisibility(View.VISIBLE);
			} else {
				lastToShow.setVisibility(View.INVISIBLE);
			}
		}
	}

	private static class GuidePagerAdapter extends PagerAdapter {
		private final List<Drawable> mEntries;

		public GuidePagerAdapter(List<Drawable> list) {
			mEntries = list;
		}

		@Override
		public int getCount() {
			return mEntries.size();
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			final ImageView view = new ImageView(container.getContext());
			view.setScaleType(ImageView.ScaleType.FIT_XY);
			view.setImageDrawable(mEntries.get(position));
			container.addView(view);
			return new ViewHolder(view, position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(((ViewHolder) object).view);
		}

		@Override
		public int getItemPosition(Object object) {
			return ((ViewHolder) object).position;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return ((ViewHolder) object).view == view;
		}

		static class ViewHolder {
			final View view;
			final int position;

			public ViewHolder(View view, int position) {
				this.view = view;
				this.position = position;
			}
		}
	}

	/////////////////////////////////////////
	// 广告部分代码
	private int mCountTime;

	private void showAd() {
		setContentView(R.layout.activity_loading);
		TextView skipTextView = findViewById(R.id.loading_skip);
		mCountTime = 5;
		final AdManager am = AdManager.instance(this);
		final Ad ad = am.getOne();
		ImageView image = findViewById(R.id.loading_image);
		if (ad == null) {
			mCountTime = 3;
			skipTextView.setVisibility(View.GONE);
			am.getAdFromNetwork(true);
		} else {
			am.getAdFromNetwork(false);
			findViewById(R.id.loading_def_view).setVisibility(View.GONE);
			ImageLoader.getInstance().displayImage(ad.getImage(), image);
			image.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					sHandler.removeCallbacks(mDelayRunnable);
					enterMain(ad.getLink());
				}
			});
			skipTextView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					sHandler.removeCallbacks(mDelayRunnable);
					enterMain(null);
				}
			});
		}
		sHandler.postDelayed(mDelayRunnable, 1000);
	}

	private Runnable mDelayRunnable = new Runnable() {
		@Override
		public void run() {
			mCountTime--;

			if (mCountTime == 0) {
				enterMain(null);
			} else {
				sHandler.postDelayed(mDelayRunnable, 1000);
			}
		}
	};

	private static void initResources(Context context) {
		MobclickAgent.updateOnlineConfig(context);
		// 更新地理坐标
		LocationUtil.getInstance(context).updateLocation();

		if (!PollService.isServiceRunning(context)) {
			PollService.startPollService(context);
		}
		NotificationService.startNotificationService(context, 10);
		UpdateService.startUpdateService(context);
		ApkRecommendHolder.getInstance().updateRecommend(context);

		if (CustomMessageDB.getInstance(context).IsTableEmpty()) {
			List<CustomMessageTb> list = CustomMessageUtils.initCustomMessageDB(context);
			if (list != null && !list.isEmpty()) {
				CustomMessageDB.getInstance(context).save(list);
				Set<String> set = new HashSet<String>();
				for (CustomMessageTb tb : list) {
					set.add(tb.getPkgName());
				}
				LockScreenConfig.setCustomMessagePkg(context, set);
			}
		}
	}

	private void enterMain(Link lnk) {
		Intent it = new Intent(this, MainActivity.class);
		if (lnk != null) {
			it.putExtra(AdManager.EXTRA_TYPE, lnk.getType());
			it.putExtra(AdManager.EXTRA_URL, lnk.getUrl());
			it.putExtra(AdManager.EXTRA_SOURCE, new ApkSource("loading_ad").toSourceString());
		}

		startActivity(it);
		finish();
		overridePendingTransition(R.anim.zoom_in, R.anim.zoom_out);
	}

	@Override
	protected void onResume() {
		super.onResume();
		JPushInterface.onResume(this);
		MobclickAgent.onResume(this);
		AppMarketApplication.showLocal = StorageConfig.SHOW_LOCAL_FILE.exists();
	}

	@Override
	protected void onPause() {
		super.onPause();
		JPushInterface.onPause(this);
		MobclickAgent.onPause(this);
	}

	private void cacheHotWords() {
		HotWordsNetEngine engine = new HotWordsNetEngine();
		NetTask mNetTask = new NetTask(this, engine, 1);
		new Thread(mNetTask).start();
	}

	@Override
	public void onBackPressed() {
		// intercept back keycode
	}

	private static int getVersionCode(Context context) {
		if (context == null) {
			return 0;
		}
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			return pi.versionCode;
		} catch (Exception e) {
		}
		return 0;
	}
}
